package com.wwwarehouse.contract.contract.modify;

import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.textinput.TextInputLayout;
import com.wwwarehouse.common.tools.rsa.StringUtils;
import com.wwwarehouse.contract.bean.InfoCardOrderDetailBean;
import com.wwwarehouse.contract.bean.SettingRuleBean;
import com.wwwarehouse.contract.contract.TheParentFragment;
import com.wwwarehouse.contract.core.ContractConstant;
import com.wwwarehouse.contract.core.ContractEventCode;
import com.wwwarehouse.contract.customview.AutoClickButton;
import com.wwwarehouse.contract.event.ContractEvent;
import com.wwwarehouse.contract.event.RefreshEvent;
import com.wwwarehouse.contract.event.RefreshIssuedGoodsEvent;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import contract.wwwarehouse.com.contract.R;
import de.greenrobot.event.EventBus;

import static android.R.attr.data;

/**
 * @author gaofeng on 2017/11/10.
 *         <p/>
 *         修改发布规则
 */

public class ModifyRulesFragment extends TheParentFragment implements View.OnClickListener {
	private TextView mLastPbPrice; //上次发布价格
	private AppCompatButton mConstantPriceBtn; //按固定价格
	private AppCompatButton mReferenceScaleBtn; //按比例
	private TextInputLayout mInputPriceLayout;//价格输入框布局
	private EditText mInputPriceEdt; //价格输入框
	private LinearLayout mPercentageLayout; //折算布局
	private TextView mPercentageTv; //折算文本
	private TextView mReallyQtyTv; //实际价格
	private TextView mCanSellQtyTv; //可售库存数
	private TextInputLayout mPublishCountLayout; //发布数量的layout
	private EditText mPublishCountEdt; //发布数量的输入框
	private AutoClickButton mConfirmBtn;
	private InfoCardOrderDetailBean.ItemDetailBean mData;
	private String mPriceRuleType;


	@Override
	public void setTitle() {
		if (peekFragment() instanceof ModifyRulesFragment) {
			mActivity.setTitle(R.string.contract_modify_info_card_modify_rules_title);
		}
	}

	@Override
	protected int getContentId() {
		return R.layout.contract_modify_rules_fragment;
	}

	@Override
	protected void init(View view) {
		mLastPbPrice = findView(view, R.id.last_pb_price_tv);
		mConstantPriceBtn = findView(view, R.id.constant_price_btn);
		mReferenceScaleBtn = findView(view, R.id.reference_scale_btn);
		mInputPriceLayout = findView(view, R.id.price_input_layout);
		mInputPriceEdt = findView(view, R.id.price_input_edt);
		mPercentageLayout = findView(view, R.id.percentage_layout);
		mPercentageTv = findView(view, R.id.percentage_tv);
		mReallyQtyTv = findView(view, R.id.really_qty_tv);
		mCanSellQtyTv = findView(view, R.id.can_sell_qty_tv);
		mPublishCountLayout = findView(view, R.id.publish_count_layout);
		mPublishCountEdt = findView(view, R.id.publish_count_edt);
		mConfirmBtn = findView(view, R.id.confirm_btn);
		mConfirmBtn.setOnClickListener(this);
		mConfirmBtn.bindEditText(mInputPriceEdt);
		mConfirmBtn.bindEditText(mPublishCountEdt);
		mConstantPriceBtn.setOnClickListener(this);
		mReferenceScaleBtn.setOnClickListener(this);
		Bundle bundle = getArguments();
		if (bundle == null || bundle.getParcelable("data") == null) {
			mLoadingView.showEmptyView(true);
			mLoadingView.setEmptyListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					requestDatas();
				}
			});
			return;
		}
		mData = bundle.getParcelable("data");
		setRule();

	}

	private void setRule() {
		if (StringUtils.isNoneNullString(mData.getPbPrice())) {
			mReferenceScaleBtn.setEnabled(true);
			mLastPbPrice.setText(StringUtils.getResourceStr(mActivity, R.string.last_publish_price_string, mData.getPbPrice()));
		} else {
			mReferenceScaleBtn.setEnabled(false);
			mLastPbPrice.setText("--元");
		}
		if (StringUtils.isNoneNullString(mData.getFactQty())) {
			//实际库存数
			if (StringUtils.isNoneNullString(mData.getUnit())) {
				mReallyQtyTv.setText("参考实际库存数:" + mData.getFactQty() + mData.getUnit());
			} else {
				mReallyQtyTv.setText("参考实际库存数:" + mData.getFactQty());
			}
		} else {
			mReallyQtyTv.setVisibility(View.GONE);
		}
		if (StringUtils.isNoneNullString(mData.getCanSoldQty())) {
			if (StringUtils.isNullString(mData.getPbQtyUnit())) {
				mCanSellQtyTv.setText("可售库存数：" + mData.getCanSoldQty());
			} else {
				mCanSellQtyTv.setText("可售库存数：" + mData.getCanSoldQty() + mData.getPbQtyUnit());
			}
		} else {
			mCanSellQtyTv.setVisibility(View.GONE);
		}
//		        价格规则类型（0、固定价格 1、参考价比例）
		if (StringUtils.isNullString(mData.getPriceRuleType())) {
			return;
		}
		mPriceRuleType = mData.getPriceRuleType();
		setPriceHint();
		if ("0".equals(mData.getPriceRuleType())) {
			mPercentageLayout.setVisibility(View.GONE);
			mConstantPriceBtn.setSelected(true);
			mReferenceScaleBtn.setSelected(false);
			mInputPriceEdt.setText(mData.getPriceRuleValue());
			mInputPriceEdt.setHint("固定的发布价格（单位：元）");
			mInputPriceLayout.updateHint();
		} else if ("1".equals(mData.getPriceRuleType())) {
			mPercentageLayout.setVisibility(View.VISIBLE);
			mConstantPriceBtn.setSelected(false);
			mReferenceScaleBtn.setSelected(true);
			mInputPriceEdt.setText(mData.getPriceRuleValue());
			mInputPriceEdt.setHint("比例 (可大于100) %");
			mInputPriceLayout.updateHint();
		}
	}

	private boolean hasToastp;
	private boolean hasToasthq;


	@Override
	protected void loadDatas() {
	}

	@Override
	public void onSuccess(CommonClass commonClass, int what) {
		if (what == 0) {
			if (TextUtils.equals("0", commonClass.getCode())) {
				popFragment();
				EventBus.getDefault().post(new ContractEvent<RefreshIssuedGoodsEvent>(ContractEventCode.CODE_REFRESH_ISSUED_GOODS  , new RefreshIssuedGoodsEvent("refresh")));
			} else {
				toast(commonClass.getMsg());
			}
		}
	}

	@Override
	public void onReLoad(int code) {

	}

	private String mLastPriceInput;
	private String mLastScalInput;
	private boolean isScalEmpty;
	private boolean isPriceEmpty;
	@Override
	public void onClick(View v) {
		int i = v.getId();
		if (StringUtils.isNullString(mData.getPriceRuleType())) {
			return;
		}
		if (StringUtils.isNullString(mData.getPriceRuleValue())) {
			return;
		}
		if (i == R.id.constant_price_btn) {
			mPercentageLayout.setVisibility(View.GONE);

			//固定价格
			mConstantPriceBtn.setSelected(true);
			mReferenceScaleBtn.setSelected(false);
			mInputPriceEdt.setHint("输入固定的发布价格（单位：元）");
			mInputPriceLayout.updateHint();
			if (mData.getPriceRuleType().equals("0")) {
				if (StringUtils.isNoneNullString(mLastPriceInput)) {
					if (mLastPriceInput.startsWith("0")) {
						mInputPriceEdt.setText("");
					} else {
						mInputPriceEdt.setText(mLastPriceInput);
					}
				} else {
					if (isPriceEmpty) {
						mInputPriceEdt.setText("");
					} else {
						mInputPriceEdt.setText(mData.getPriceRuleValue());
					}
				}
				mInputPriceEdt.setHint("固定的发布价格（单位：元）");
				mInputPriceLayout.updateHint();
			} else {
				if (StringUtils.isNoneNullString(mLastPriceInput)) {
					mInputPriceEdt.setText(mLastPriceInput);
				} else {
					mInputPriceEdt.setText("");
				}
				mInputPriceEdt.setHint("固定的发布价格（单位：元）");
				mInputPriceLayout.updateHint();
			}
			if (StringUtils.isNoneNullString(mInputPriceEdt.getText().toString())) {
				mInputPriceEdt.setSelection(mInputPriceEdt.getText().toString().length());
			}
		} else if (i == R.id.reference_scale_btn) {
			//按比例
			mPercentageLayout.setVisibility(View.VISIBLE);
			mConstantPriceBtn.setSelected(false);
			mReferenceScaleBtn.setSelected(true);
			mInputPriceEdt.setHint("输入比例 (可大于100) %");
			mInputPriceLayout.updateHint();
			if (mData.getPriceRuleType().equals("1")) {
				if (StringUtils.isNoneNullString(mLastScalInput)) {
					if (mLastScalInput.startsWith("0")) {
						mInputPriceEdt.setText("");
					} else {
						mInputPriceEdt.setText(mLastScalInput);
					}
				} else {
					if (isScalEmpty) {
						mInputPriceEdt.setText("");
					} else {
						mInputPriceEdt.setText(mData.getPriceRuleValue());
					}
				}
				mInputPriceEdt.setHint("比例 (可大于100) %");
				mInputPriceLayout.updateHint();
			} else {
				mInputPriceEdt.setText("");
				mInputPriceEdt.setHint("比例 (可大于100) %");
				mInputPriceLayout.updateHint();
			}
			if (StringUtils.isNoneNullString(mInputPriceEdt.getText().toString())) {
				mInputPriceEdt.setSelection(mInputPriceEdt.getText().toString().length());
			}
		}
		if (i == R.id.confirm_btn) {
			if (mData != null) {
				Map<String, Object> map = new HashMap<>();
				map.put("itemPublishUkid", mData.getItemPublishUkid());
				if (mInputPriceEdt.getText().toString().startsWith("00")) {
					toast("价格必须大于零");
					return;
				}
				if (!mReferenceScaleBtn.isSelected()) {
					map.put("pbPrice", mInputPriceEdt.getText().toString().trim());
				} else {
					if (StringUtils.isNoneNullString(mPercentageTv.getText().toString().trim())) {
						map.put("pbPrice", mPercentageTv.getText().toString().trim());
					} else {
						map.put("pbPrice", mInputPriceEdt.getText().toString().trim());
					}
				}
				if (mPublishCountEdt.getText().toString().startsWith("0")) {
					toast("数量必须大于零");
					return;
				}
//				if (!mQtyTypeProportion.isSelected()) {
//					map.put("pbQty", mEdtQty.getText().toString().trim());
//				} else {
//					try {
//						map.put("pbQty", Integer.parseInt(mEdtQty.getText().toString().trim()) * Integer.parseInt(data.getPbQty()));
//					} catch (Exception e) {
//						map.put("pbQty", mEdtePrice.getText().toString().trim());
//					}
//				}
				map.put("pbPriceOld", mData.getPbPrice());
				map.put("pbQty", mPublishCountEdt.getText().toString().trim());
				map.put("pbQtyUnit", mData.getPbQtyUnit());
				map.put("pbQtyUnitUkid", mData.getPbQtyUnitUkid());
				if (mConstantPriceBtn.isSelected()) {
					map.put("priceRuleType", 0);
				} else if (mReferenceScaleBtn.isSelected()) {
					map.put("priceRuleType", 1);
				}
				map.put("priceRuleValue", mInputPriceEdt.getText().toString().trim());
				httpPost(ContractConstant.METHOD_RESOURCE_UPDATA_PUBLISHITEM_RULE, map, 0, true, "");
			}

		}
// else if (i == R.id.price_type_fixed) {
//			mTilPrice.setVisibility(View.VISIBLE);
//			mLLPrice.setVisibility(View.GONE);
//			priceRuleType = "0";
//			mTypeFixed.setSelected(true);
//			mTypeProportion.setSelected(false);
//			mEdtePrice.setHint("输入固定的发布价格（单位：元）");
//			mTilPrice.updateHint();
//			if (!TextUtils.isEmpty(mPriceValue) && !"0".equals(mPriceValue)) {
//				mEdtePrice.setText(mPriceValue);
//				mEdtePrice.setHint("固定的发布价格（单位：元）");
//				mTilPrice.updateHint();
//			}
//
//		} else if (i == R.id.price_type_proportion) {
//			mTilPrice.setVisibility(View.VISIBLE);
//			priceRuleType = "1";
//			mLLPrice.setVisibility(View.VISIBLE);
//			mTypeFixed.setSelected(false);
//			mTypeProportion.setSelected(true);
//			mEdtePrice.setHint("输入比例 (可大于100) %");
//			mTilPrice.updateHint();
//			if (!TextUtils.isEmpty(mPriceProValue) && !"0".equals(mPriceProValue)) {
//				mEdtePrice.setText(mPriceProValue);
//				mEdtePrice.setHint("比例 (可大于100) %");
//				mTilPrice.updateHint();
//			}
//		} else if (i == R.id.qty_type_fixed) {
//			mTilQty.setVisibility(View.VISIBLE);
//			qtyRuleType = "0";
//			mLLPb.setVisibility(View.GONE);
//			mTilQty.updateHint();
//			if (!TextUtils.isEmpty(mQtyCount) && !"0".equals(mQtyCount)) {
//				mEdtePrice.setText(mQtyCount);
//				mTilQty.updateHint();
//			}
//
//		} else if (i == R.id.qty_type_proportion) {
//			mTilQty.setVisibility(View.VISIBLE);
//			mLLPb.setVisibility(View.VISIBLE);
//			qtyRuleType = "1";
//			mEdtQty.setInputType(8194);
//			mTilQty.updateHint();
//			if (!TextUtils.isEmpty(mQtyCountPro) && !"0".equals(mQtyCountPro)) {
//				mEdtePrice.setText(mQtyCountPro);
//				mTilQty.updateHint();
//			}
//		}
	}

	private void setPriceHint() {
		mInputPriceEdt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (mReferenceScaleBtn.isSelected()) {
					if (hasFocus) {
						mInputPriceEdt.setHint("比例 (可大于100) %");
						mInputPriceLayout.updateHint();
					} else {
						if (TextUtils.isEmpty(mInputPriceEdt.getText().toString())) {
							mInputPriceEdt.setHint("输入比例 (可大于100) %");
							mInputPriceLayout.updateHint();
						} else {
							mInputPriceEdt.setHint("比例 (可大于100) %");
							mInputPriceLayout.updateHint();
						}

					}
				} else if (mConstantPriceBtn.isSelected()) {
					if (hasFocus) {
						mInputPriceEdt.setHint("固定的发布价格（单位：元）");
						mInputPriceLayout.updateHint();
					} else {
						if (TextUtils.isEmpty(mInputPriceEdt.getText().toString())) {
							mInputPriceEdt.setHint("输入固定的发布价格（单位：元）");
							mInputPriceLayout.updateHint();
						} else {
							mInputPriceEdt.setHint("固定的发布价格（单位：元）");
							mInputPriceLayout.updateHint();
						}

					}
				}

			}
		});

		mInputPriceEdt.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				if (mConstantPriceBtn.isSelected()) {
					mInputPriceEdt.setHint("固定的发布价格（单位：元）");
					mInputPriceLayout.updateHint();
				} else if (mReferenceScaleBtn.isSelected()) {
					mInputPriceEdt.setHint("比例 (可大于100) %");
					mInputPriceLayout.updateHint();
				}

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (mReferenceScaleBtn.isSelected()) {
					if (mReferenceScaleBtn.isSelected()) {
						try {
							float p = Float.parseFloat(s.toString());
							DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
							if (StringUtils.isNullString(mData.getPbPrice())) {
								return;
							}
							double mPrice = Double.valueOf(mData.getPbPrice());
							mPercentageTv.setText(String.format("%s", decimalFormat.format(p * mPrice / 100)));

						} catch (Exception e) {
							mPercentageTv.setText("--");
						}
//					mPriceBili = s.toString().trim();
					} else {
//					mPriceGuding = s.toString().trim();
					}
				}
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (mConstantPriceBtn.isSelected()) {
					if (StringUtils.isNullString(s.toString())) {
						isPriceEmpty = true;
					} else {
						isPriceEmpty = false;
					}
					if (s.toString().startsWith("00") && !hasToasthq) {
						hasToasthq = true;
						toast("价格必须大于零");
					} else if (!s.toString().startsWith("00")) {
						hasToasthq = false;
						mLastPriceInput = s.toString();
//					mPriceValue = s.toString().trim();
					}
				} else if (mReferenceScaleBtn.isSelected()) {
					if (StringUtils.isNullString(s.toString())) {
						isScalEmpty = true;
					} else {
						isScalEmpty = false;
					}
					if (s.toString().startsWith("00") && !hasToastp) {
						hasToastp = true;
						toast("价格必须大于零");
					} else if (!s.toString().startsWith("00")) {
						hasToastp = false;
						mLastScalInput = s.toString();

					}
				}

			}
		});
	}
}
